package com.chatplus.application.service.basedata.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chatplus.application.aiprocessor.constant.AIConstants;
import com.chatplus.application.common.constant.GroupCacheNames;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.common.util.CacheGroupUtils;
import com.chatplus.application.common.util.PlusJsonUtils;
import com.chatplus.application.dao.basedata.ApiKeyDao;
import com.chatplus.application.domain.dto.AdminConfigDto;
import com.chatplus.application.domain.dto.ChatConfigDto;
import com.chatplus.application.domain.entity.basedata.ApiKeyEntity;
import com.chatplus.application.enumeration.AiPlatformEnum;
import com.chatplus.application.service.basedata.ApiKeyService;
import com.chatplus.application.service.basedata.ConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * OpenAI API 业务逻辑实现
 *
 * <p>Table: t_api_key - OpenAI API </p>
 *
 * @author developer
 * @see ApiKeyEntity
 */
@Service
public class ApiKeyServiceImpl extends ServiceImpl<ApiKeyDao, ApiKeyEntity> implements ApiKeyService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ApiKeyServiceImpl.class);

    private final ConfigService configService;

    public ApiKeyServiceImpl(ConfigService configService) {
        this.configService = configService;
    }

    @Override
    public void init() {
        LOGGER.message("开始加载AI相关配置到缓存").info();
        ChatConfigDto chatConfigDto = configService.getChatConfig();
        if (chatConfigDto == null) {
            LOGGER.message("加载AI参数配置失败").error();
        } else {
            // 总的缓存
            CacheGroupUtils.put(GroupCacheNames.SYS_AI_SETTING, AIConstants.CHAT_CONFIG_REDIS_KEY, chatConfigDto);
            // 以下为细分的缓存
            CacheGroupUtils.put(GroupCacheNames.SYS_AI_SETTING, AiPlatformEnum.AZURE, chatConfigDto.getAzure());
            CacheGroupUtils.put(GroupCacheNames.SYS_AI_SETTING, AiPlatformEnum.BAI_DU, chatConfigDto.getBaidu());
            CacheGroupUtils.put(GroupCacheNames.SYS_AI_SETTING, AiPlatformEnum.CHAT_GLM, chatConfigDto.getChatGml());
            CacheGroupUtils.put(GroupCacheNames.SYS_AI_SETTING, AiPlatformEnum.OPEN_AI, chatConfigDto.getOpenAi());
            CacheGroupUtils.put(GroupCacheNames.SYS_AI_SETTING, AiPlatformEnum.XUN_FEI, chatConfigDto.getXunFei());
        }
        AdminConfigDto adminConfigDto = configService.getSystemConfig();
        if (adminConfigDto == null) {
            LOGGER.message("加载系统参数配置失败").error();
        } else {
            CacheGroupUtils.put(GroupCacheNames.SYS_AI_SETTING, AIConstants.SYSTEM_CONFIG_REDIS_KEY, adminConfigDto);
        }
        List<ApiKeyEntity> apiChatKeys = this.getEnableApiKeys(null, "chat");
        if (CollectionUtils.isEmpty(apiChatKeys)) {
            LOGGER.message("系统已经没有可用的 API Chat KEY!!！");
        } else {
            Map<AiPlatformEnum, List<ApiKeyEntity>> map = apiChatKeys.stream()
                    .collect(Collectors.groupingBy(ApiKeyEntity::getPlatform));
            map.forEach((k, v) -> CacheGroupUtils.put(GroupCacheNames.SYS_AI_CHAT_API_KEY, k, PlusJsonUtils.toJsonString(v)));
        }
        List<ApiKeyEntity> apiImgKeys = this.getEnableApiKeys(null, "image");
        if (CollectionUtils.isEmpty(apiImgKeys)) {
            LOGGER.message("系统已经没有可用的 API Image KEY!!！");
        } else {
            Map<AiPlatformEnum, List<ApiKeyEntity>> map = apiImgKeys.stream()
                    .collect(Collectors.groupingBy(ApiKeyEntity::getPlatform));
            map.forEach((k, v) -> CacheGroupUtils.put(GroupCacheNames.SYS_AI_IMAGE_API_KEY, k, PlusJsonUtils.toJsonString(v)));
        }
        LOGGER.message("结束加载AI相关配置到缓存").info();
    }

    @Override
    public List<ApiKeyEntity> getEnableApiKeys(String platform, String type) {
        return list(new LambdaQueryWrapper<ApiKeyEntity>()
                .eq(StringUtils.isNotEmpty(platform), ApiKeyEntity::getPlatform, platform)
                .eq(ApiKeyEntity::getEnabled, true)
                .eq(StringUtils.isNotEmpty(type), ApiKeyEntity::getType, type));

    }
}
